package com.easyOrder.core.filter;

import com.google.gson.Gson;
import com.easyOrder.core.cache.IRedisCacheClient;
import com.easyOrder.core.duplicate.DuplicateSubmissionAnnotation;
import com.easyOrder.core.duplicate.DuplicateSubmissionToken;
import com.easyOrder.core.duplicate.DuplicateSubmissionTokenProcessor;
import com.easyOrder.core.exception.api.DuplicateSubmissionException;
import com.easyOrder.core.utils.WebUtils;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


/**
 * 避免重复提交拦截器
 */
public class DuplicateSubmissionInterceptor extends HandlerInterceptorAdapter {

    private static final int AVOID_DUPLICATE_TIME = 6;

    @Autowired
    private IRedisCacheClient cacheClient;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Gson gson = new Gson();
            DuplicateSubmissionAnnotation annotation = method.getAnnotation(DuplicateSubmissionAnnotation.class);
            if (null != annotation) {
                String sessionId = WebUtils.Session.get().getId();
                boolean validateToken = annotation.validateToken();
                if (validateToken) {
                    String cacheKey = DuplicateSubmissionTokenProcessor.getCacheKey(sessionId, annotation.businessType());
                    JSONObject jsonObject = JSONObject.fromObject(cacheClient.get(cacheKey));
                    DuplicateSubmissionToken token = (DuplicateSubmissionToken) JSONObject.toBean(jsonObject, DuplicateSubmissionToken.class);
                    if (token == null) {
                        token = new DuplicateSubmissionToken();
                        token.getSubmited().set(true);
                        jsonObject = JSONObject.fromObject(token);
                        cacheClient.set(cacheKey, jsonObject.toString(), AVOID_DUPLICATE_TIME);
                    } else {
                        throw new DuplicateSubmissionException();
                    }
//                    throw new InvalidSubmissionTokenException();
                }
            }
        }
        return true;
    }

    private boolean isDupilicateSubmit(HttpServletRequest request, DuplicateSubmissionToken cacheToken) {
        if (cacheToken != null) {
            return true;
        }
        return false;
    }
}